import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8086/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// API接口
export const authApi = {
  login: (credentials) => api.post('/auth/login', credentials),
  register: (userData) => api.post('/auth/register', userData)
}

export const profileApi = {
  get: () => api.get('/user/profile'),
  update: (profileData) => api.put('/user/profile', profileData),
  getByUsername: (username) => api.get(`/../jpa/users/${username}/profile/details`)
}

export const postApi = {
  getAll: () => api.get('/post/list'),
  getById: (id) => api.get(`/post/${id}`),
  create: (postData) => api.post('/post/create', postData),
  like: (id) => api.post(`/post/${id}/like`),
  unlike: (id) => api.delete(`/post/${id}/like`),
  comment: (commentData) => api.post('/post/comment', commentData),
  getComments: (postId) => api.get(`/post/${postId}/comments`),
  getNotifications: () => api.get('/notification'),
  markNotificationAsRead: (id) => api.post(`/notification/${id}/read`)
}

export const commentApi = {
  add: (postId, content) => api.post('/post/comment', { postId, content }),
  getByPost: (postId) => api.get(`/post/${postId}/comments`)
}

export const notificationApi = {
  getAll: () => api.get('/notification'),
  markRead: (id) => api.post(`/notification/${id}/read`),
  create: (notification) => api.post('/notification', notification)
}

export const fileApi = {
  upload: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/file/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  }
}

export const messageApi = {
  send: ({ to, content }) => api.post('/message/send', null, { params: { toUser: to, content } }),
  list: (to) => api.get(`/message/history/${to}`)
}

export default api 